<?php defined('SYSPATH') OR die('No direct access allowed.');
class user
{
	/**
	 * 设置用户信息
	 *
	 * @param array 	user_info
	 */
	static public function set_user($user_info)
	{
		$session = Session::instance();
		foreach($user_info as $key=>$val)
		{
			$session->set($key,$val);
		}
	}

	/**
	 * 设置Cookie，以便下次登陆，使用mcrypt加密，这样即使不小心泄露了apikey，也没有多大影响
	 * @param string 用户的apikey
	 */ 
	static public function set_login_cookie($apikey)
	{
		cookie::set('auth',Encrypt::instance()->encode($apikey));
	}

	/**
	 * 判断用户是否登陆
	 */
	static public function is_login()
	{
		return Session::instance()->get('userId');
	}

	/**
	 * 通过cookie自动登录
	 */
	static public function auto_login()
	{
		if(!(self::is_login()) && (cookie::get('auth','')!=''))
		{
			$apikey = Encrypt::instance()->decode(cookie::get('auth'));
			$user = ORM::factory('user')->select('id','username','email')->where('apikey',$apikey)->find();
			if(is_int($user->id))
			{
				self::set_user(array('userId'=>$user->id,'username'=>$user->username,'email'=>$user->email));
			}
		}
	}
}
